package com.blackhorse.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试nacos配置中心的controller，使用时打开RestController注解
 */
@RestController
@RefreshScope //@Value动态刷新注解
public class NacosConfigController {

    @Autowired
    public ConfigurableApplicationContext applicationContext;

    @Value("${config.appName}")
    public String appName;
    @Value("${config.env}")
    public String env;
    @Value("${school.name}")
    public String schoolName;

    @GetMapping("/test-config1")
    public String getConfig1() {
        //获取nacos配置
        //方法1，通过environment获取，默认支持动态更新
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        return environment.getProperty("config.appName");
    }

    @GetMapping("/test-config2")
    public String getConfig2() {
        //获取nacos配置
        //方法2，通@Value注入，默认不支持动态更新；如果需要动态更新，则需要在类上添加@RefreshScope
        return appName;
    }

    @GetMapping("/test-config3")
    public String getConfig3() {
        //测试多环境共享配置和独享配置
        return env;
    }

    @GetMapping("/test-config4")
    public String getConfig4() {
        //测试多个服务共享配置文件
        return schoolName;
    }
}
